package com.example.larou.utils;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.ConsumerStopAction;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
@IntegrationComponentScan
@Slf4j
public class MqttConfig {
    @Value("{${spring.mqtt.username}")
    private String username;
    @Value("{${spring.mqtt.password}")
    private String password;
    @Value("{${spring.mqtt.url}")
    private String host;
    @Value("{${spring.mqtt.clientid}")
    private String clientid;
    @Value("{${spring.mqtt.defaultTopic}}")
    private String defaultTopic;


    @Bean
    public MqttConnectOptions getMqttConnect(){
        //mqtt连接配置
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[] { "tcp://183.230.40.96:1883"});
        mqttConnectOptions.setKeepAliveInterval(60);
        mqttConnectOptions.setConnectionTimeout(30);
        return mqttConnectOptions;
    }
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory(){
        //创建mqtt默认工厂
        DefaultMqttPahoClientFactory defaultMqttPahoClientFactory=new DefaultMqttPahoClientFactory();
        defaultMqttPahoClientFactory.setConnectionOptions(getMqttConnect());
        return defaultMqttPahoClientFactory;
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttMsgChannel")
    public MessageHandler mqttMsg(){
        //mqtt消息处理
        MqttPahoMessageHandler mqttPahoMessageHandler=new MqttPahoMessageHandler(clientid,mqttPahoClientFactory());
        mqttPahoMessageHandler.setAsync(true);
        mqttPahoMessageHandler.setDefaultTopic(defaultTopic);
        return mqttPahoMessageHandler;
    }
    @Bean
    public MessageChannel mqttMsgChannel(){
        return new DirectChannel();
    }
}

